<?php
ini_set('display_errors','off');
include_once dirname(__FILE__)."/../../core/lib/db.connect/cnn.config.php";

function makeSafe($theValue) {
	global $cartMain,$langArray;
	for ($f = 0; $f < count($langArray); $f++) {
		if ($cartMain["languageID"] == $langArray[$f]["languageID"] && $langArray[$f]["doubleByte"] == "Y") {
			return htmlentities($theValue);
			break;
		}
	}
	return htmlentities(str_replace(array(";","<?","?>"),"",$theValue));
}
function getFORM($vName) {
	$val = (@$_GET[$vName] != "") ? @$_GET[$vName] : @$_POST[$vName];
	return $val;
}



// Configuration definitions, move to config.php
$CONFIG['security']['password_generator'] = array(
	"C" => array('characters' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'minimum' => 5, 'maximum' => 5),
	"S" => array('characters' => "!@()-_=+?*^&", 'minimum' => 1, 'maximum' => 1),
	"N" => array('characters' => '1234567890', 'minimum' => 2, 'maximum' => 2)
);

function STEM_GeneratePassword()
{
	// Create the meta-password
	$sMetaPassword = "";

	global $CONFIG;
	$ahPasswordGenerator = $CONFIG['security']['password_generator'];
	foreach ($ahPasswordGenerator as $cToken => $ahPasswordSeed)
	$sMetaPassword .= str_repeat($cToken, rand($ahPasswordSeed['minimum'], $ahPasswordSeed['maximum']));

	$sMetaPassword = str_shuffle($sMetaPassword);

	// Create the real password
	$arBuffer = array();
	for ($i = 0; $i < strlen($sMetaPassword); $i ++)
	$arBuffer[] = $ahPasswordGenerator[(string)$sMetaPassword[$i]]['characters'][rand(0, strlen($ahPasswordGenerator[$sMetaPassword[$i]]['characters']) - 1)];

	return implode("", $arBuffer);
}

function verifConnect()
{
	/*if(isset($_SESSION['valid_user']) && $_SESSION["idsession"] == session_id() && $_SESSION["isConnected_appproj"] == 1 && $_SESSION['expires'] > time())
	{
		$_SESSION['expires'] = time()+(4*60);
		

	}
	elseif(isset($_SESSION['valid_user']) && $_SESSION["idsession"] == session_id() && $_SESSION["isConnected_appproj"] == 1 && $_SESSION['expires'] <= time())
	{*/
		//$_SESSION["idsession"] = "";
		//$_SESSION["isConnected_appproj"] = 0;
		//unset($_SESSION);
		//session_destroy();
		//return FALSE;

	/*}
	else
	return FALSE;*/
	if(isset($_SESSION["isConnected_appproj"]) && $_SESSION["isConnected_appproj"]){
		return TRUE;
	}
	
}

function disconnect()
{
	$_SESSION["idsession"] = "";
	$_SESSION["isConnected_appproj"] = 0;
	unset($_SESSION);
	session_destroy();
}

function verifLogin()
{


if (isset($_POST['username']) && isset($_POST['password']))
{
	$userid = makeSafe($_POST['username']);
	$pass = makeSafe($_POST['password']);
	//$pass = sha1($pass);
	if (strlen($userid)>0 && strlen($pass)>0)
	{
		$db_conn = mysql_connect(_HOST_,_USER_, _PWD_);
  		mysql_select_db(_DBNAME_, $db_conn);
		$query = "SELECT * FROM personne WHERE login='".mysql_real_escape_string($userid)."' AND MotPasse='".mysql_real_escape_string($pass)."'";
		$result = mysql_query($query);
		if (mysql_num_rows($result)>0)
		{
		
			$_SESSION['valid_user'] = $userid;
			$_SESSION["idsession"] = session_id();
			$_SESSION["isConnected_appproj"] = 1;
			//$_SESSION['expires'] = time()+(2*60);
			$row=mysql_fetch_object($result);
		  
			$_SESSION['cin']=$row->CIN;
			$_SESSION['email']=$row->Mail;
				$_SESSION['nom']=$row->Nom;
					$_SESSION['prenom']=$row->Prenom;
				
			//if($row->id_inscription!=NULL) $_SESSION['id_iscription']=$row->id_inscription;
			//mysql_query('update username set is_connected = 1 WHERE id_user='.$row->id_user) ;
		}
	}
}
}

function verifLogin_CAS()
{
include_once('CAS.php');

phpCAS::setDebug();

// initialize phpCAS
phpCAS::client(CAS_VERSION_2_0,'ent.uvt.rnu.tn',443,'/cas');

// no SSL validation for the CAS server
phpCAS::setNoCasServerValidation();

// force CAS authentication
phpCAS::forceAuthentication();

// at this step, the user has been authenticated by the CAS server
// and the user's login name can be read with phpCAS::getUser().
$usager_uid = phpCAS::getUser();




/***
 * Verfication dans la base local de l'existance de l'enseignant
 */
$db_conn = mysql_connect(_HOST_,_USER_, _PWD_);
mysql_select_db(_DBNAME_);

$query = "SELECT * FROM personne WHERE CIN='$usager_uid'";
//die($query);
//die("erreur LOCAL ".mysql_error());
$result = mysql_query($query);

if (mysql_num_rows($result)<=0){
	mysql_close($db_conn);
	$db_cnn_ent = mysql_connect(_HOST_ENT_,_USER_ENT_, _PWD_ENT_);
  	mysql_select_db(_DBNAME_ENT_);
	//die("erreur ".mysql_error());
	$sql_select = "select * from personne where CIN = '$usager_uid'";
	//die($sql_select);
	$req=mysql_query($sql_select,$db_cnn_ent);
	//die("erreur ".mysql_error());
	 while( $res=mysql_fetch_array($req)) {
	 	$sql_insert_ens="
			INSERT INTO personne(
				Civilite,
				Titre,
				Nom,
				Prenom,
				CIN,
				MotPasse,
				Mail,
				AdressePostale,
				NumTelephone,
				NumFax,
				NumMobile,
				CategorieUsager,
				CategoriePrincipaleUsager,
				IdentifiantInstitutionnel,
				OrganismeRattachement,
				LMD,
				Discipline,
				Pays,
				ville
			)
			VALUES(
				'".$res['Civilite']."',
				'".$res['Titre']."',
				'".$res['Nom']."',
				'".$res['Prenom']."',
				'".$res['CIN']."',
				'".$res['MotPasse']."',
				'".$res['Mail']."',
				'".$res['AdressePostale']."',
				'".$res['NumTelephone']."',
				'".$res['NumFax']."',
				'".$res['NumMobile']."',
				'".$res['CategorieUsager']."',
				'".$res['CategoriePrincipaleUsager']."',
				'".$res['IdentifiantInstitutionnel']."',
				'".$res['OrganismeRattachement']."',
				'".$res['LMD']."',
				'".$res['Discipline']."',
				'".$res['Pays']."',
				'".$res['ville']."'
			)
		";
		die($sql);
		try{
			$req=mysql_query($sql_insert_ens);
			
		}catch(exception $e){
			mysql_close($db_cnn_ent);
			
		}
	 }
	 mysql_close($db_cnn_ent);
}
/**
 * 
 */
			$_SESSION['cin']=$usager_uid;
			/////////////////  fin code casification ////////////////
			$_SESSION['valid_user'] = $usager_uid;
			$_SESSION["idsession"] = session_id();
			$_SESSION["isConnected_appproj"] = 1;
			$_SESSION['expires'] = time()+(10*60);
			$row=mysql_fetch_object($result);
		  

}


?>